package com.gzdh.device.wx.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gzdh.device.comm.vo.Result;
import com.gzdh.device.wx.entity.WxChangeGoldPlan;
import com.gzdh.device.wx.entity.WxSubMchid;
import com.gzdh.device.wx.service.WxChangeGoldPlanService;
import com.gzdh.device.wx.service.WxSubMchidService;
import com.gzdh.device.wx.vo.ChangeGoldPlanVO;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.goldplan.GoldPlanService;
import com.wechat.pay.java.service.goldplan.model.ChangeGoldPlanStatusRequest;
import com.wechat.pay.java.service.goldplan.model.ChangeGoldPlanStatusResponse;
import com.wechat.pay.java.service.goldplan.model.OperationPayScene;
import com.wechat.pay.java.service.goldplan.model.OperationType;
import com.wechat.pay.java.service.refund.RefundService;
import com.xxl.job.core.biz.model.ReturnT;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 处理微信后台得基本操作
 */
@RestController
@RequestMapping("api/wx/ChangeGoldPlan/v1")
public class WxSubMchidController {


    @Autowired
    WxSubMchidService wxSubMchidService;

    @Autowired
    WxChangeGoldPlanService wxChangeGoldPlanService;

    /**
     * 获取商户基本信息列表
     *
     * @return
     */
    @GetMapping("changeGoldPlanList")
    public Result<Object> changeGoldPlanList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                             @RequestParam(name = "name", required = false) String name) {
        Result<Object> result = new Result<>();
        IPage<WxSubMchid> wxSubMchidIPage = new Page<>(pageNo, pageSize);
        wxSubMchidIPage = wxSubMchidService.page(wxSubMchidIPage, new QueryWrapper<WxSubMchid>().lambda()
                .eq(StringUtils.isNotEmpty(name), WxSubMchid::getName, name));
        IPage<ChangeGoldPlanVO> changeGoldPlanVOIPage = new Page<>();
        BeanUtils.copyProperties(wxSubMchidIPage, changeGoldPlanVOIPage);
        List<ChangeGoldPlanVO> changeGoldPlanVOList = new ArrayList<>();
        for (WxSubMchid goo : wxSubMchidIPage.getRecords()) {
            ChangeGoldPlanVO changeGoldPlanVO = new ChangeGoldPlanVO();
            BeanUtils.copyProperties(goo, changeGoldPlanVO);
            WxChangeGoldPlan wxChangeGoldPlan = wxChangeGoldPlanService.getOne(new QueryWrapper<WxChangeGoldPlan>().lambda()
                    .eq(WxChangeGoldPlan::getWxMchId, goo.getId()));
            if (wxChangeGoldPlan == null) {
                continue;
            }
            changeGoldPlanVO.setJsapiStatus(wxChangeGoldPlan.getJsapiStatus());
            changeGoldPlanVO.setMiniprogramStatus(wxChangeGoldPlan.getMiniprogramStatus());
            changeGoldPlanVO.setUrl(wxChangeGoldPlan.getUrl());
            changeGoldPlanVOList.add(changeGoldPlanVO);
        }
        changeGoldPlanVOIPage.setRecords(changeGoldPlanVOList);
        result.setResult(changeGoldPlanVOIPage);
        return result;
    }

    @PostMapping("changegoldplanstatus")
    public Result<Object> changegoldplanstatus(@RequestBody JSONObject jsonObject) {
        Result<Object> result = new Result<>();
        String mchId = jsonObject.getString("id");
        boolean status = jsonObject.getBoolean("status");
        int type = jsonObject.getInteger("type");

        try {
            WxSubMchid wxSubMchid = wxSubMchidService.getById(mchId);
            Config config =
                    new RSAAutoCertificateConfig.Builder()
                            .merchantId("146395120")
                            .privateKey("MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC2wVGPRkTWAZkR\n" +
                                    "Q8C5tYb4LM3d3kJdcuuesMj69XA3Cc3eLyBO3X8/ald1XJ4qptKoYm9yvE1wmLjo\n" +
                                    "33PSCamji63FSuC/79wSoRZoNCDE7im4PMvvC+8Ab8MFss4JCAUjNVeSqm9EYiy3\n" +
                                    "yl93PWw64CfjC9HMZXVl2Kf5G5GMQgYwUj+7vM/iFPHlm+nW9+4w8zO48JN7AC2G\n" +
                                    "X/mupEgW2znuFwHRmtQgk34K0cFoTUb/dWvAqPlTZHb+PlnjtVxisiemAP9KP+ev\n" +
                                    "pZ4iyuJ7ED1vB32q/M1csaCUE31YR2xb0npTiKOxUBUbiD31AWzV2KTlSzv+hza4\n" +
                                    "AC7rU9y/AgMBAAECggEAMz4xaEMDuh3olXax62CC38NwVe2kHh/DAVQAhp2bQVN2\n" +
                                    "bf44yORCcb2XmEjH8J2mI6C2Ly2taQzpjCJbj2E2N61KpC9CpY7T3kVcywsSxSUi\n" +
                                    "fY5OgFCQS0cLH+Xq741YI28phu5TFJGSiFYuPnjyh++iP39o7C7mpBADyU15miHP\n" +
                                    "3BV9LHquCaLS9PGpuxetAtMgauI4W6P3ee3bSJIY8fkpwT9KXE2ZyddI71ttYm28\n" +
                                    "i8S2AKECHeXJVbrZMWh8o7ylx3VOia3JFTdvYMAsNwzWtfE+YXm/erKhVKtTlFUO\n" +
                                    "oNF+ugAcXZSUTzcTLLUe1zE1UA8EjNi/8Lob8EH0AQKBgQDas7zxF8A7mL0Co38q\n" +
                                    "Wrc3K43e4nRKkyhutrT2BU80NBZslxep0w3JMvRUKyPPx0Qk+V3kCJrbZnDB/MDf\n" +
                                    "IlvwHNTa3iZ3uSMIEICALnMDAe8O+H71+Amnhqv+f9J2doA2LcMSn0LlVbsN9Bp+\n" +
                                    "hQLfYB4suabgjQIrsbP/nB8WwQKBgQDV7C5r7Kdlh2izFCFyhNCYVmr4XL7i9X2m\n" +
                                    "i2Lx9n31Z0DLME9QeiYzgPF8ehaHcoSFo42H3hLCcMxgQUrldv0rdjc3/mvGxeE1\n" +
                                    "nngVQkC70fC7aH3FSvcljRrAoEgLdMV/p6ZtAUzmLW3FdQ/ftIgkv55uyoJNAzjb\n" +
                                    "MS1cFEdTfwKBgE4NCWhNnqhmSUZQzUhzWaHR5G7gCLq4rBxfDlQi7vJliH82qRZN\n" +
                                    "oUTl73a+cqhrqDE94blJLOMSOzmwF7FKlN8rmveFgtsFcrAlG4cjjJ5NKWEBZGYq\n" +
                                    "IF/uWyGXwqfOgNFVIaJavkgUgY5oSLBQjgbkScCSfTD0ggrP/7pAoIPBAoGBAIf8\n" +
                                    "BtZcLV0A4rFTjp95hhAQfxc5/a3QV/tSh6dABXnGFQ4Uu5Zwz2/V+6wg/8lCJrO8\n" +
                                    "7+76X/pyMbjOSIntRaonD5rshB5rE2o+Ph9lajj6j4jSN4D+0nRwah0gxitiI1mu\n" +
                                    "fMC2HugC4NCwRVLzM8gIdvH+kS3ban0LmcX6rgyJAoGAQq+KrfKxHLWKXmWtKYng\n" +
                                    "U08eA2gIQllFRH4MeKAQJS8+wzUnVv3SdvWeBDNx8S1cWxxV5KhTGvDK6m4moC0d\n" +
                                    "WrGoPRe9hohgCngw0q+jl7ewLYZq+EbhlcjSf/pHOXmAWgRyLnnlE1f33HagduqE\n" +
                                    "erW1qxvba1QaJ41mesy3aXw=")
                            .merchantSerialNumber("4243CFD7D2D61AD35B00DCD5A1F4B19FBBCE2F23")
                            .apiV3Key("asdfghjkl0asdfghjkl0asdfghjkl012")
                            .build();


            GoldPlanService service = new GoldPlanService.Builder().config(config).build();
            ChangeGoldPlanStatusRequest changeGoldPlanStatusRequest = getChangeGoldPlanStatusRequest(status, type, wxSubMchid);
            ChangeGoldPlanStatusResponse changeGoldPlanStatusResponse = service.changeGoldPlanStatus(changeGoldPlanStatusRequest);
            System.out.println(changeGoldPlanStatusResponse.toString());
            if (StringUtils.isNotEmpty(changeGoldPlanStatusResponse.getSubMchid()) && type == 0) {
                //修改成功，更改标志
                wxChangeGoldPlanService.lambdaUpdate().set(WxChangeGoldPlan::getJsapiStatus, status).eq(WxChangeGoldPlan::getWxMchId, wxSubMchid.getId()).update();
            } else if (type == 1) {
                wxChangeGoldPlanService.lambdaUpdate().set(WxChangeGoldPlan::getMiniprogramStatus, status).eq(WxChangeGoldPlan::getWxMchId, wxSubMchid.getId()).update();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @NotNull
    private static ChangeGoldPlanStatusRequest getChangeGoldPlanStatusRequest(boolean status, int type, WxSubMchid wxSubMchid) {
        ChangeGoldPlanStatusRequest changeGoldPlanStatusRequest = new ChangeGoldPlanStatusRequest();
        changeGoldPlanStatusRequest.setSubMchid(wxSubMchid.getSubMchid());
        if (status) {
            changeGoldPlanStatusRequest.setOperationType(OperationType.OPEN);
        } else {
            changeGoldPlanStatusRequest.setOperationType(OperationType.CLOSE);
        }
        if (type == 0) {
            changeGoldPlanStatusRequest.setOperationPayScene(OperationPayScene.JSAPI);
        } else {
            changeGoldPlanStatusRequest.setOperationPayScene(OperationPayScene.MINIPROGRAM);
        }
        return changeGoldPlanStatusRequest;
    }
}
